<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-11-27
 * Time: 10:14
 */

namespace app\api\controller\v1;


use app\api\service\phone\ChangePhoneSer;
use app\api\service\phone\GetPhoneCodeSer;
use app\api\service\UserToken;
use app\api\validate\phone\CheckPhone;
use app\api\validate\TokenGet;
use app\api\service\Token as TokenService;
use app\lib\exception\ParameterException;
use app\api\model\User;

class Token
{
    /**
     * 小程序获取token
     * @url /token/user
     * @http post
     * @code 小程序的code
     */
    public function getToken($code)
    {
        (new TokenGet())->goCheck();
        $ut = new UserToken($code);
        $token = $ut->get();
        return [
            'token' => $token
        ];
    }

    /**
     * 验证小程序token
     * @url /token/verify
     * @token 小程序的token
     */
    public function verifyToken($token)
    {
        if(!$token)
        {
            throw new ParameterException([
                'token' => 'token不允许为空'
            ]);
        }
        $valid = TokenService::verifyToken($token);
        return [
            'isValid' => $valid
        ];
    }

    /**
     * 获取验证码
     */
    public function getSmsCode($phone)
    {
        (new CheckPhone())->goCheck();
        $userPhone = new GetPhoneCodeSer($phone);
        return $userPhone->getSms();
    }


    /**
     * 修改手机号
     */
    public function getChangeTel($phone)
    {
        (new CheckPhone())->goCheck();
        $uid = TokenService::getCurrentUid();
        $user = User::where('id',$uid)->with('member')->find();
        if(!$user['member']) {
            throw new ParameterException([
                'msg' => [
                    'tel' => '会员还未申请'
                ]
            ]);
        }
        if($user['member']['phone'] == $phone) {
            throw new ParameterException([
                'msg' => [
                    'tel' => '新手机号和原手机号相同'
                ]
            ]);
        }
        $userPhone = new GetPhoneCodeSer($phone);
        return $userPhone->getSms();
    }

    /**
     * 验证并修改手机号信息
     */
    public function changeTel($phone,$code)
    {
        $userPhone = new ChangePhoneSer($phone,$code);
        return $userPhone->setSmsChange();
    }
}